﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Xml.Linq;

namespace Framework.WebmasterTool
{
    public partial class NewsLetter : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFramework.DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                CallCkeditors();
                LoadNewsLetters();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.NewsLetter.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CallCkeditors()
        {
            Globals.CallCKFinder(txtBody);
        }

        public void LoadNewsLetters()
        {
            XDocument xDocNewsLetter = XDocument.Load(Server.MapPath(ConfigPaths.Path_Newsletter_Xml));
            var listNewsLetter = xDocNewsLetter.Descendants("email").Select(nl => new { value = nl.Element("value").Value }).ToList();
            grvNewsLetter.DataSource = listNewsLetter;
            grvNewsLetter.DataBind();
            if (listNewsLetter.Count == 0)
            {
                btnSend.Enabled = false;
            }

        }

        protected void grvNewsLetter_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvNewsLetter.PageIndex = e.NewPageIndex;
            LoadNewsLetters();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            XDocument xDocNewsLetter = XDocument.Load(Server.MapPath(ConfigPaths.Path_Newsletter_Xml));
            var newsLetter = xDocNewsLetter.Descendants("email").Where(nl => nl.Element("value").Value.Trim() == txtEmail.Text.Trim()).FirstOrDefault();
            if (newsLetter == null)
            {
                lblMessage.Text = "";
                xDocNewsLetter.Root.Add(new XElement("email",
                new XElement("value", txtEmail.Text.Trim())));
                xDocNewsLetter.Save(Server.MapPath(ConfigPaths.Path_Newsletter_Xml));

                //create db log 
                CreateDBLog(null, null, TypeAction.Insert, "Thêm email gửi thư hàng loạt: " + txtEmail.Text.Trim(), "", "", "", "", "", "", "", "");

                Response.Redirect("NewsLetter.aspx");
            }
            else
            {
                lblMessage.Text = "Email này đã tồn tại";
                txtEmail.Text = "";
            }
        }

        protected void imbEdit_Command(object sender, CommandEventArgs e)
        {
            var value = e.CommandArgument.ToString().Trim();
            XDocument xDocNewsLetter = XDocument.Load(Server.MapPath(ConfigPaths.Path_Newsletter_Xml));
            var newsLetter = xDocNewsLetter.Descendants("email").Where(nl => nl.Element("value").Value.Trim() == value).FirstOrDefault();
            if (newsLetter != null)
            {
                //create db log 
                CreateDBLog(null, null, TypeAction.Delete, "Xoá email gửi thư hàng loạt: " + value, "", "", "", "", "", "", "", "");

                newsLetter.Remove();
                xDocNewsLetter.Save(Server.MapPath(ConfigPaths.Path_Newsletter_Xml));
            }
            LoadNewsLetters();
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            udv_EmailHostSetting emailHostSetting = entity.udv_EmailHostSetting.OrderByDescending(es => es.EmailHostSettingID).FirstOrDefault();
            string serverMail = emailHostSetting.ServerMailSMTP.Trim();
            string port = emailHostSetting.PortMailSMTP.ToString();
            string yourMailAccount = emailHostSetting.MailAccount.Trim();
            string yourMailPassword = Globals.Base64Decode(emailHostSetting.Password);
            string mailReceivers = "";

            SendMail sm = new SendMail();
            sm.ServerMail = serverMail;
            sm.ServerPort = port;
            sm.SSL = emailHostSetting.SSL.Value;
            sm.YourMailAccount = yourMailAccount;
            sm.YourMailPassword = yourMailPassword;
            sm.SetUpYourServerMail();

            foreach (GridViewRow item in grvNewsLetter.Rows)
            {
                mailReceivers += ((Label)item.FindControl("lblEmail")).Text + ",";
            }

            sm.CreateMailObject(mailReceivers, txtBody.Text, txtTitleNewsletter.Text.Trim(), emailHostSetting.MailReceive);
            if (sm.MailSending())
            {
                //create db log 
                CreateDBLog(null, null, TypeAction.None, "Gửi thư hàng loạt: " + txtTitleNewsletter.Text, "", txtBody.Text, "", "", "", "", "", "");

                lblMessage2.Text = "Gửi bản tin thành công";
                txtBody.Text = txtEmail.Text = txtTitleNewsletter.Text = "";
            }
            else
            {
                lblMessage2.Text = "Lỗi cấu hình mail server. Vui lòng cấu hình lại mail server và thử lại sau";
            }

        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}